//
//  IMAdjustService.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/27.
//

#import "IMAdjustService.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import <Foundation/Foundation.h>

// 如果项目中集成了Adjust SDK，取消下面的注释
// #import <Adjust/Adjust.h>

@interface IMAdjustService ()

@property (nonatomic, assign) BOOL adjustInitialized;
@property (nonatomic, strong) dispatch_queue_t adjustQueue;

@end

@implementation IMAdjustService

static IMAdjustService *_sharedService = nil;
static dispatch_once_t _onceToken;

+ (instancetype)sharedService {
    dispatch_once(&_onceToken, ^{
        _sharedService = [[IMAdjustService alloc] init];
    });
    return _sharedService;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _adjustInitialized = NO;
        _adjustQueue = dispatch_queue_create("com.dualmediationsdk.adjust", DISPATCH_QUEUE_SERIAL);
        [IMLogUtils info:IMLogTagAd format:@"IMAdjustService initialized"];
    }
    return self;
}

#pragma mark - Public Methods

- (BOOL)isAdjustInitialized {
    return self.adjustInitialized;
}

- (void)setAdjustInitialized:(BOOL)initialized {
    self.adjustInitialized = initialized;
    [IMLogUtils info:IMLogTagAd format:@"Adjust initialization status updated: %@", initialized ? @"YES" : @"NO"];
}

- (IMAdjustResult *)trackEvent:(NSString *)eventId {
    IMAdjustEventConfig *config = [IMAdjustEventConfig configWithEventId:eventId];
    return [self trackEventWithConfig:config];
}

- (void)trackEvent:(NSString *)eventId completion:(IMAdjustCompletionBlock)completion {
    IMAdjustEventConfig *config = [IMAdjustEventConfig configWithEventId:eventId];
    [self trackEventWithConfig:config completion:completion];
}

- (IMAdjustResult *)trackEvent:(NSString *)eventId parameters:(NSDictionary<NSString *,NSString *> *)parameters {
    IMAdjustEventConfig *config = [IMAdjustEventConfig configWithEventId:eventId parameters:parameters];
    return [self trackEventWithConfig:config];
}

- (void)trackEvent:(NSString *)eventId parameters:(NSDictionary<NSString *,NSString *> *)parameters completion:(IMAdjustCompletionBlock)completion {
    IMAdjustEventConfig *config = [IMAdjustEventConfig configWithEventId:eventId parameters:parameters];
    [self trackEventWithConfig:config completion:completion];
}

- (IMAdjustResult *)trackRevenueEvent:(NSString *)eventId revenue:(NSNumber *)revenue currency:(NSString *)currency {
    IMAdjustEventConfig *config = [IMAdjustEventConfig configWithEventId:eventId revenue:revenue currency:currency];
    return [self trackEventWithConfig:config];
}

- (void)trackRevenueEvent:(NSString *)eventId revenue:(NSNumber *)revenue currency:(NSString *)currency completion:(IMAdjustCompletionBlock)completion {
    IMAdjustEventConfig *config = [IMAdjustEventConfig configWithEventId:eventId revenue:revenue currency:currency];
    [self trackEventWithConfig:config completion:completion];
}

- (IMAdjustResult *)trackEventWithConfig:(IMAdjustEventConfig *)config {
    // 参数验证
    if (!config) {
        IMAdjustResult *result = [IMAdjustResult failureWithCode:-1000 message:@"事件配置不能为空"];
        [IMLogUtils error:IMLogTagAd format:@"Adjust事件上报失败: 配置为空"];
        return result;
    }
    
    if (![config isValid]) {
        IMAdjustResult *result = [IMAdjustResult failureWithCode:-1001 message:@"事件配置无效"];
        [IMLogUtils error:IMLogTagAd format:@"Adjust事件上报失败: 配置无效 %@", config];
        return result;
    }
    
    // 检查初始化状态
    if (!self.adjustInitialized) {
        IMAdjustResult *result = [IMAdjustResult failureWithCode:-1002 message:@"Adjust未初始化"];
        [IMLogUtils error:IMLogTagAd format:@"Adjust事件上报失败: Adjust未初始化"];
        return result;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"开始上报Adjust事件: %@", config];
    
    // 执行事件上报
    BOOL success = [self performTrackEvent:config];
    
    if (success) {
        [IMLogUtils info:IMLogTagAd format:@"Adjust事件上报成功: %@", config.eventId];
        return [IMAdjustResult successWithEventId:config.eventId];
    } else {
        [IMLogUtils error:IMLogTagAd format:@"Adjust事件上报失败: %@", config.eventId];
        return [IMAdjustResult failureWithCode:-1003 message:@"事件上报失败"];
    }
}

- (void)trackEventWithConfig:(IMAdjustEventConfig *)config completion:(IMAdjustCompletionBlock)completion {
    dispatch_async(self.adjustQueue, ^{
        IMAdjustResult *result = [self trackEventWithConfig:config];
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result);
            });
        }
    });
}

#pragma mark - Private Methods

- (BOOL)performTrackEvent:(IMAdjustEventConfig *)config {
    @try {
        // 这里是实际的Adjust事件上报逻辑
        // 如果项目中集成了Adjust SDK，取消下面的注释并修改相应代码
        
        /*
        ADJEvent *adjustEvent = [[ADJEvent alloc] initWithEventToken:config.eventId];
        
        // 添加参数
        if (config.parameters && config.parameters.count > 0) {
            for (NSString *key in config.parameters) {
                [adjustEvent addCallbackParameter:key value:config.parameters[key]];
            }
        }
        
        // 添加收入信息
        if (config.revenue && config.currency) {
            [adjustEvent setRevenue:[config.revenue doubleValue] currency:config.currency];
        }
        
        [Adjust trackEvent:adjustEvent];
        */
        
        // 模拟上报（实际项目中应该调用真实的Adjust SDK）
        [IMLogUtils info:IMLogTagAd format:@"模拟Adjust事件上报: eventId=%@", config.eventId];
        
        if (config.parameters && config.parameters.count > 0) {
            [IMLogUtils info:IMLogTagAd format:@"事件参数: %@", config.parameters];
        }
        
        if (config.revenue && config.currency) {
            [IMLogUtils info:IMLogTagAd format:@"收入信息: %@ %@", config.revenue, config.currency];
        }
        
        return YES;
        
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"Adjust事件上报异常: %@", exception.reason];
        return NO;
    }
}

@end